<?php

namespace EasySwoole\EasySwoole;


use App\Process\HotReload;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use App\Logger\Logger;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
        //注入自定义日志处理
        Di::getInstance()->set(SysConst::LOGGER_HANDLER, new Logger());

        // 控制器命名空间
        //Di::getInstance()->set(SysConst::HTTP_CONTROLLER_NAMESPACE, 'App\\Http\\Controllers\\');
    }

    // 切换Mysql链接
    public static function setMysqlConnection(string $connection_name = 'default')
    {
        if (!empty(DbManager::getInstance()->getConnection($connection_name))) {
            return $connection_name;
        } else return 'default';
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.

        $server = ServerManager::getInstance()->getSwooleServer();

        /**
         * 热更新设置【代码变更，无需重启】
         */
        $hotReloadOptions = new \EasySwoole\HotReload\HotReloadOptions;
        $hotReload        = new \EasySwoole\HotReload\HotReload($hotReloadOptions);
        $hotReloadOptions->setMonitorFolder([EASYSWOOLE_ROOT . '/App']);
        $hotReload->attachToServer($server);

        // 服务热重启【代码变更，无需重启】
        //$server->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());


        /**
         * 注册数据库连接池
         */
        $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('Mysql.default'));
        DbManager::getInstance()->addConnection(new Connection($config), 'default');

        $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('Mysql.write'));
        DbManager::getInstance()->addConnection(new Connection($config), 'write');


        DbManager::getInstance()->onQuery(function ($res, $builder, $start)
        {
            // 打印参数 OR 写入日志

            // 记录SQL语句
            Logger::getInstance()->log($builder->getLastQuery(), Logger::LOG_LEVEL_NOTICE, 'Mysql', 'sql_log');
        });
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        // 拦截所有请求添加跨域头
        $response->withHeader('Access-Control-Allow-Origin', '*');
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Access-Control-Allow-Headers, x-xsrf-token, Accept, x-file-name, x-frame-options, X-Requested-With');
        if ($request->getMethod() === 'OPTIONS') {
            $response->withStatus(200);
            return false;
        }
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}